#!/usr/bin/perl -w
# CCNv2::Provision::Asterisk::erouter.pm
# Copyright (C) 2006  Stephane Alnet
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 3
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
# 

#
# For more information: http://carrierclass.net/
#
package CCNv2::Provision::Asterisk::erouter;
use strict; use warnings;
use CCNCore::Provision::Base;
use base qw(CCNCore::Provision::Base);
use CCNv2::Parameters;
use CCN::Text;
use CCNCore::Scripting;

sub run()
{
    my $self = shift;
    return unless defined $self->p->{cp_member};

    # Outbound routing is done in [router-emergency] (in the 'library')
    # directly from asterisk_from_proxy.pm

    # Inbound routing is here :)

    my $conf = '';
    
    $self->sql_do_for( <<'SQL',
        SELECT erl.enterprise, erl."number", elin."number" FROM elin, erl
        WHERE erouter = ? AND elin.erl = erl.pk;
SQL
    $self->p->server_name, sub
    {
        my $ENTERPRISE_pk = shift;
        my $ERL_number = shift;

        $conf = "[${ENTERPRISE_pk}-elin]\n";

        my $ELIN = shift;
        my $ENTERPRISE_id = CCNv2::Parameters::enterprise_id($ENTERPRISE_pk);
        # Send the ELIN to the ERouter
        $conf .= 
            "exten => ${ELIN},1,Goto(enterprise-${ENTERPRISE_id}-to-proxy,ELi${ENTERPRISE_id}k${ELIN},1)\n";
    });

    foreach("/etc/asterisk/config/extensions.elin.conf")
    {
        CAT $_, copyright(';') . $conf;
        IF_CHANGED $_ => CCNv2::Scripting::AST('extensions reload');
    }
}
1;
